﻿namespace Sidvall.Data.Sqlite
{
    public sealed class TransactionManager : Sidvall.Data.ITransactionScope
    {
        #region Business Members

        #region Connection

        private global::SQLite.Net.SQLiteConnection _Connection;
        public global::SQLite.Net.SQLiteConnection Connection
        {
            get
            {
                return _Connection;
            }
            set
            {
                _Connection = value;
                if (_Connection != null)
                {
                    if (!_Connection.IsInTransaction)
                        _Connection.BeginTransaction();
                }
            }
        }

        #endregion
        #region IsCompleted

        private bool _IsCompleted;
        public bool IsCompleted
        {
            get
            {
                return _IsCompleted;
            }
            private set
            {
                _IsCompleted = value;
            }
        }

        #endregion

        #region Complete

        public void Complete()
        {
            this.IsCompleted = true;
        }

        #endregion
        #region Dispose

        public void Dispose()
        {
            if (Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction != null)
            {
                if (this.Connection != null)
                {
                    if (this.IsCompleted)
                        this.Connection.Commit();
                    else
                    {
                        try
                        {
                            this.Connection.Rollback();
                        }
                        catch
                        {
                        }
                    }
                    this.Connection.Close();
                    this.Connection = null;
                }
                Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction = null;
            }
            System.GC.SuppressFinalize(this);
        }

        #endregion
        #region ToString

        public override string ToString()
        {
            return "TransactionManager - SQLite.Net.SQLiteConnection";
        }

        #endregion

        #endregion
        #region Factory Members

        #region GetTransactionScope

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static TransactionManager GetTransactionScope()
        {
            var item = new TransactionManager()
            {
                IsCompleted = false,
            };
            Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction = item;
            return item;
        }

        #endregion

        #endregion
    }
}
